package com.zhuoyue.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory());
        Map<String,String> map = new HashMap<>();
        try {
            List<FileItem> list=upload.parseRequest(request);
            for (FileItem fi:list){
                if(fi.isFormField()){//普通控件  用户名 密码
                    String name = fi.getFieldName();//获取表单中数据的name属性值  username   password
                    String value= fi.getString("utf-8");//获取value属性值，文本框中填写的内容  张三   123456
                    map.put(name,value);
                    System.out.println(name+"\t"+value);
                }else{//文件控件  上传的文件
                    String name = fi.getName();//获取上传文件的名字
                    String path = "/server";//获取文件路径  Tomcat中项目路径
                    path = path+"/"+name;
                    File file = new File(path);
                    fi.write(file);//写出文件
                    map.put("file",name);
                    System.out.println("file"+"\t"+name);
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
